﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;


namespace Jemgine.MapEditor.Operations
{
	internal class PropertyChanged : Operation
	{
		Object Owner;
		Dictionary<String, Object> OldValues;
		Dictionary<String, Object> NewValues;

		internal static Dictionary<String, Object> GetPropertySet(Object obj)
		{
			Dictionary<String, Object> Set = new Dictionary<string, object>();

			var Descriptors = TypeDescriptor.GetProperties(obj);

            foreach (PropertyDescriptor Desc in Descriptors)
            {
                if (Desc.IsBrowsable)
                    Set[Desc.Name] = Desc.GetValue(obj);
            }

			return Set;
		}

		internal PropertyChanged(Object Owner, Dictionary<String, Object> OldValues, Dictionary<String, Object> NewValues)
		{
			this.Owner = Owner;
			this.OldValues = OldValues;
			this.NewValues = NewValues;
		}

		internal override ReturnCode Do(EditorState ES)
		{
			var Descriptors = TypeDescriptor.GetProperties(Owner);
			foreach (KeyValuePair<String, Object> Pair in NewValues)
				Descriptors.Find(Pair.Key, false).SetValue(Owner, Pair.Value);

            var Attributes = Owner.GetType().GetCustomAttributes(true);
            foreach (var Attr in Attributes)
                if (Attr is Engine.EditorInitializationAttribute)
                    ( Attr as Engine.EditorInitializationAttribute ).OnPropertyChange(Owner, new EditorStateInterface(ES));

			return ReturnCode.AddToUndoStack;
		}

		internal override void Undo(EditorState ES)
		{
			var Descriptors = TypeDescriptor.GetProperties(Owner);
			foreach (KeyValuePair<String, Object> Pair in OldValues)
				Descriptors.Find(Pair.Key, false).SetValue(Owner, Pair.Value);

            var Attributes = Owner.GetType().GetCustomAttributes(true);
            foreach (var Attr in Attributes)
                if (Attr is Engine.EditorInitializationAttribute)
                    ( Attr as Engine.EditorInitializationAttribute ).OnPropertyChange(Owner, new EditorStateInterface(ES));
		}



	}
}
